package com.tsoj.tsojgateway.filter;


import com.tsoj.context.ThreadLocalContext;
import com.tsoj.propertise.JwtPropertise;
import com.tsoj.utils.JwtUtils;
import com.tsoj.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * 全局响应拦截器
 */
@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Resource
    private JwtPropertise jwtPropertise;
    //不用鉴权接口
    private static final List<String> skipAuthPaths = Arrays.asList(
            "/api/doc.html",
            "/api/user/login",
            "/api/user/register",
            "/api/question/list/page/vo",
            "/swagger-resources/**",
            "/api/**/v2/api-docs/**",  // 新增：匹配 /api/**/v2/api-docs/** 路径
            "/api/**/v3/api-docs/**",
            "/v2/api-docs/**",
            "/v3/api-docs/**"
    );
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest serverHttpRequest = exchange.getRequest();
        String path = serverHttpRequest.getURI().getPath();

        // 判断路径是否为免登录路径
        if (isSkipAuthPath(path)) {
            return chain.filter(exchange); // 跳过鉴权，直接放行
        }
        // 判断路径中是否包含 inner，只允许内部调用
        if (antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.FORBIDDEN);
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            DataBuffer dataBuffer = dataBufferFactory.wrap("无权限".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
        // todo 统一权限校验，通过 JWT 获取登录用户信息
        HttpHeaders headers = serverHttpRequest.getHeaders();
        String token = headers.getFirst(jwtPropertise.getUserTokenName());
        if (token == null) {
            return unauthorizedResponse(exchange, "缺少 Token");
        }

        Claims claims = JwtUtils.parseJwt(jwtPropertise.getUserSecretKey(), token);
        Long userId = Long.valueOf(claims.get("userId").toString());
        //todo 待优化使用方法 优化id在上下文传递最安全的方法

        //todo 做redis重验证
        boolean isHave = redisUtils.hasKey(token);
        if(!isHave){
            return unauthorizedResponse(exchange, "Token 无效");
        }
        ThreadLocalContext.setUserId(userId);

        return chain.filter(exchange);
    }
    private boolean isSkipAuthPath(String path) {
        return skipAuthPaths.stream().anyMatch(p -> antPathMatcher.match(p, path));
    }
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer buffer = response.bufferFactory().wrap(message.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
    /**
     * 优先级提到最高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
